﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

public partial class PageUserRegister_UserRegister : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    
        //可以驗證沒輸入帳號
        txtAccount.Attributes["onchange"] = "if ( IsValid(this) == false ) return;";
        
        //解決證驗的錯誤
        UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
       
       //不讓密碼被AutoPost洗掉
       txtPassword.Attributes["value"] = txtPassword.Text;
       txtPasswordConfirm.Attributes["value"] = txtPasswordConfirm.Text;

        if (!IsPostBack)
        {
            txtAccount.Text = "";
            txtEmail.Text = "";
            txtLastName.Text = "";
            txtPassword.Text = "";
            txtPasswordConfirm.Text = "";
            txtFirstName.Text = "";
            txtPhone.Text = "";
            SetYear();
            SetMonth();
            SetDay();
        }
    }
    public void SetYear()
    {
        for (int i = 1900; i <= DateTime.Now.Year; i++)
        {
            cboYear.Items.Add(i.ToString());
        }
    }

    //设置月份
    public void SetMonth()
    {
        for (int i = 1; i <= 12; i++)
        {
            cboMonth.Items.Add(i.ToString());
        }
    }
    //设置日份
    public void SetDay()
    {
        for (int i = 1; i <= 30; i++)
        {
            cboDay.Items.Add(i.ToString());
        }
    }
    //修改日份
    public void ChangeDay()
    {
        cboDay.Items.Clear();  //每次判断之前先清空天数，避免重复赋值
        switch (int.Parse(cboMonth.SelectedValue))
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                {
                    for (int i = 1; i <= 31; i++)
                    {
                        cboDay.Items.Add(i.ToString());
                    }
                    break;
                }
            case 2:
                {
                    if (IsLeapYear(int.Parse(cboYear.SelectedValue)))
                    {
                        for (int i = 1; i <= 29; i++)
                        {
                            cboDay.Items.Add(i.ToString());
                        }
                    }
                    else
                    {
                        for (int i = 1; i <= 28; i++)
                        {
                            cboDay.Items.Add(i.ToString());
                        }
                    }
                    break;
                }
            default:
                {
                    for (int i = 1; i <= 30; i++)
                    {
                        cboDay.Items.Add(i.ToString());
                    }
                    break;
                }
        }
    }
    //判断是否为闰年
    public bool IsLeapYear(int year)
    {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    protected void cmdSend_Click(object sender, EventArgs e)
    {
        //連接資料庫
        if (Page.IsValid)
        {
            //Conn.Open();

            char sex = 'M';
            if (txtPassword.Text != txtPasswordConfirm.Text)
            {
                Response.Write("密碼與確認密碼不符");
                return;
            }
            SqlConnection Conn = new SqlConnection(LinkToDatabase.strConn);
            try
            {
                Random i = new Random(Guid.NewGuid().GetHashCode());
                int random = i.Next(0, 9999999);
                DateTime registrationdate = DateTime.Now;
                bool visible = true;
                string s = "Insert Into [dbo].[user](user_username,user_password,user_password_random,user_first_name,user_last_name,user_birthday,user_sex,user_mobile_phone,user_email,user_visible,user_registration_date) Values(@Username,@Password,@Random,@Firstname,@Lastname,@Birthday,@Sex,@Phone,@Email,@Visible,@RegistrationDate)";
                SqlCommand sqlcmd = new SqlCommand(s, Conn);
                //宣告參數
                sqlcmd.Parameters.Add("@Username", System.Data.SqlDbType.NVarChar);
                sqlcmd.Parameters.Add("@Password", System.Data.SqlDbType.NVarChar);
                sqlcmd.Parameters.Add("@Firstname", System.Data.SqlDbType.NChar);
                sqlcmd.Parameters.Add("@Lastname", System.Data.SqlDbType.NChar);
                sqlcmd.Parameters.Add("@Birthday", System.Data.SqlDbType.DateTime);
                sqlcmd.Parameters.Add("@Random", System.Data.SqlDbType.NVarChar);
                sqlcmd.Parameters.Add("@Sex", System.Data.SqlDbType.NVarChar);
                sqlcmd.Parameters.Add("@Phone", System.Data.SqlDbType.NChar);
                sqlcmd.Parameters.Add("@Email", System.Data.SqlDbType.NVarChar);
                sqlcmd.Parameters.Add("@RegistrationDate", System.Data.SqlDbType.DateTime);
                sqlcmd.Parameters.Add("@Visible", System.Data.SqlDbType.Bit);
                //給參數作傳遞
                sqlcmd.Parameters["@Username"].Value = txtAccount.Text;
                string hash = getMd5Hash(txtPassword.Text, random);
                sqlcmd.Parameters["@Password"].Value = hash;
                sqlcmd.Parameters["@Firstname"].Value = txtFirstName.Text;
                sqlcmd.Parameters["@Lastname"].Value = txtLastName.Text;
                sqlcmd.Parameters["@Birthday"].Value = cboYear.SelectedValue + '/' + cboMonth.SelectedValue + '/' + cboDay.SelectedValue;
                sqlcmd.Parameters["@Random"].Value = random;
                sqlcmd.Parameters["@Phone"].Value = txtPhone.Text;
                sqlcmd.Parameters["@Email"].Value = txtEmail.Text;
                sqlcmd.Parameters["@RegistrationDate"].Value = registrationdate;
                sqlcmd.Parameters["@Visible"].Value = visible;

                if (optWoman.Checked)
                {
                    sex = 'F';
                }
                sqlcmd.Parameters["@Sex"].Value = sex;
                sqlcmd.Connection.Open();


                //檢查帳號是否重複，重複擋掉
                SqlConnection Conn2 = new SqlConnection(LinkToDatabase.strConn);
                Conn2.Open();
                string s2 = "select user_username from [user] WHERE user_username='" + txtAccount.Text + "'";
                SqlDataReader dr = null;
                SqlCommand cmd = new SqlCommand(s2, Conn2);
                dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    Response.Write("<script>alert('相同的帳號');</script>");
                    cmd.Cancel();
                    //----關閉DataReader之前，一定要先「取消」SqlCommand
                    dr.Close();
                    Conn2.Close();
                    Conn2.Dispose();
                    return;
                }
                //成功則修改資料並存入資料庫並且跳轉主頁面
                try
                {
                    
                    sqlcmd.ExecuteNonQuery();
                    Response.Write("<script>alert('加入會員成功!');location.href='index.aspx'; </script>");                    
                }
                catch
                {
                    Response.Write("錯誤");

                }
            }
            finally
            {
                Conn.Close();
            }
        }
    }
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("index.aspx");
    }
    protected void cmdClear_Click(object sender, EventArgs e)
    {
        txtAccount.Text = "";
        txtEmail.Text = "";
        txtLastName.Text = "";
        txtPassword.Text = "";
        txtPasswordConfirm.Text = "";
        txtFirstName.Text = "";
        txtPhone.Text = "";
    }
    protected void txtAccount_TextChanged(object sender, EventArgs e)
    {
        SqlConnection Conn = new SqlConnection(LinkToDatabase.strConn);
        Conn.Open();
        string s = "select user_username from [dbo].[user] WHERE user_username='" + txtAccount.Text + "'";
        SqlDataReader dr = null;
        SqlCommand cmd = new SqlCommand(s, Conn);
        dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {

            Label15.Text = ("相同的帳號");
            cmd.Cancel();
            //----關閉DataReader之前，一定要先「取消」SqlCommand
            dr.Close();
            Conn.Close();
            Conn.Dispose();
        }
        else
        {
            Label15.Text = ("可以使用的帳號");
        }
    }

    //MD5加密的方法
    protected String getMd5Hash(String uInput, int salt)
    {
        string hashPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(uInput + salt, "sha1");

        return hashPassword;
    }


    protected void cboYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        ChangeDay();
    }
    protected void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
    {
        ChangeDay();
    }
   
}